/*=========================================================================

  Library:   HMP

  Copyright (c) Kitware Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0.txt

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

=========================================================================*/

// Qt includes
#include <QMutexLocker>
#include <QThread>
#include <QHash>

// HMP includes
#include "ErrorLogContext.h"
#include "ErrorLogStreamMessageHandler.h"
#include "Utils.h"

// STD includes
#include <iostream>
#include <streambuf>
#include <string>

namespace
{

// --------------------------------------------------------------------------
// StreamHandler

//
// See http://lists.trolltech.com/qt-interest/2005-06/thread00166-0.html
//

// --------------------------------------------------------------------------
class StreamHandler : public std::streambuf
{
public:
  StreamHandler(ErrorLogStreamMessageHandler* messageHandler,
                   ErrorLogLevel::LogLevel logLevel,
                   std::ostream& stream);

  void setEnabled(bool value);

protected:
  virtual int_type overflow(int_type v);
  virtual std::streamsize xsputn(const char *p, std::streamsize n);

private:
  void initBuffer();
  std::string* currentBuffer();

  ErrorLogStreamMessageHandler * MessageHandler;
  ErrorLogLevel::LogLevel LogLevel;
  ErrorLogContext LogContext;

  bool Enabled;

  std::ostream&   Stream;
  std::streambuf* SavedBuffer;
  QHash<Qt::HANDLE, std::string*> StringBuffers;
  QMutex Mutex;
};

// --------------------------------------------------------------------------
// StreamHandler methods

// --------------------------------------------------------------------------
StreamHandler::StreamHandler(ErrorLogStreamMessageHandler* messageHandler,
                                   ErrorLogLevel::LogLevel logLevel,
                                   std::ostream& stream) :
  MessageHandler(messageHandler), LogLevel(logLevel), Stream(stream)
{
  this->Enabled = false;
}

// --------------------------------------------------------------------------
void StreamHandler::setEnabled(bool value)
{
  if (this->Enabled == value)
    {
    return;
    }

  if (value)
    {
    this->SavedBuffer = this->Stream.rdbuf();
    this->Stream.rdbuf(this);
    }
  else
    {
    // Output anything that is left
//    if (!this->StringBuffer.empty())
//      {
//      Q_ASSERT(this->MessageHandler);
//      this->MessageHandler->handleMessage(this->LogLevel,
//          this->MessageHandler->handlerPrettyName(), this->StringBuffer.c_str());
//      }
    this->Stream.rdbuf(this->SavedBuffer);
    }

  this->Enabled = value;
}

// --------------------------------------------------------------------------
void StreamHandler::initBuffer()
{
  Qt::HANDLE threadId = QThread::currentThreadId();
  if (!this->StringBuffers.contains(threadId))
    {
    this->StringBuffers.insert(threadId, new std::string);
    }
}

// --------------------------------------------------------------------------
std::string* StreamHandler::currentBuffer()
{
  return this->StringBuffers.value(QThread::currentThreadId());
}

// --------------------------------------------------------------------------
std::streambuf::int_type StreamHandler::overflow(std::streambuf::int_type v)
{
  QMutexLocker locker(&this->Mutex);
  this->initBuffer();
  if (v == '\n')
    {
    Q_ASSERT(this->MessageHandler);
    this->MessageHandler->handleMessage(
          HMP::qtHandleToString(QThread::currentThreadId()), this->LogLevel,
          this->MessageHandler->handlerPrettyName(),
          ErrorLogContext(this->currentBuffer()->c_str()), this->currentBuffer()->c_str());
    this->currentBuffer()->erase(this->currentBuffer()->begin(), this->currentBuffer()->end());
    }
  else
    {
    *this->currentBuffer() += v;
    }
  return v;
}

// --------------------------------------------------------------------------
std::streamsize StreamHandler::xsputn(const char *p, std::streamsize n)
{
  QMutexLocker locker(&this->Mutex);
  this->initBuffer();
  this->currentBuffer()->append(p, p + n);

  std::string::size_type pos = 0;
  while (pos != std::string::npos)
    {
    pos = this->currentBuffer()->find('\n');
    if (pos != std::string::npos)
      {
      std::string tmp(this->currentBuffer()->begin(), this->currentBuffer()->begin() + pos);
      Q_ASSERT(this->MessageHandler);
      this->MessageHandler->handleMessage(
            HMP::qtHandleToString(QThread::currentThreadId()), this->LogLevel,
            this->MessageHandler->handlerPrettyName(),
            ErrorLogContext(tmp.c_str()), tmp.c_str());
      this->currentBuffer()->erase(this->currentBuffer()->begin(), this->currentBuffer()->begin() + pos + 1);
      }
    }
  return n;
}

}

// --------------------------------------------------------------------------
// ErrorLogStreamMessageHandlerPrivate

// --------------------------------------------------------------------------
class ErrorLogStreamMessageHandlerPrivate
{
public:
  ErrorLogStreamMessageHandlerPrivate();
  ~ErrorLogStreamMessageHandlerPrivate();

  StreamHandler * CoutStreamHandler;
  StreamHandler * CerrStreamHandler;
};

// --------------------------------------------------------------------------
// ErrorLogStreamMessageHandlerPrivate methods

//------------------------------------------------------------------------------
ErrorLogStreamMessageHandlerPrivate::ErrorLogStreamMessageHandlerPrivate()
{
}

//------------------------------------------------------------------------------
ErrorLogStreamMessageHandlerPrivate::~ErrorLogStreamMessageHandlerPrivate()
{
  delete this->CoutStreamHandler;
  delete this->CerrStreamHandler;
}

//------------------------------------------------------------------------------
// ErrorLogStreamMessageHandler methods

//------------------------------------------------------------------------------
QString ErrorLogStreamMessageHandler::HandlerName = QLatin1String("Stream");

// --------------------------------------------------------------------------
ErrorLogStreamMessageHandler::ErrorLogStreamMessageHandler() :
  Superclass(), d_ptr(new ErrorLogStreamMessageHandlerPrivate())
{
  Q_D(ErrorLogStreamMessageHandler);
  d->CoutStreamHandler = new StreamHandler(this, ErrorLogLevel::Info, std::cout);
  d->CerrStreamHandler = new StreamHandler(this, ErrorLogLevel::Critical, std::cerr);
}

// --------------------------------------------------------------------------
ErrorLogStreamMessageHandler::~ErrorLogStreamMessageHandler()
{
}

// --------------------------------------------------------------------------
QString ErrorLogStreamMessageHandler::handlerName()const
{
  return ErrorLogStreamMessageHandler::HandlerName;
}

// --------------------------------------------------------------------------
void ErrorLogStreamMessageHandler::setEnabledInternal(bool value)
{
  Q_D(ErrorLogStreamMessageHandler);
  d->CoutStreamHandler->setEnabled(value);
  d->CerrStreamHandler->setEnabled(value);
}
